﻿using DynamicChart.Service;
using DynamicChart.Service.FunctionConversion;
using DynamicChart.Service.Interpreter;
using DynamicChart.Repository;
using DynamicChart.Util;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace DynamicChart
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // 添加 CORS 策略
            services.AddCors(options =>
            {
                options.AddPolicy("AllowLocalhost5173", policy =>
                {
                    policy.WithOrigins("http://localhost:5173") // 允许前端地址
                          .AllowAnyHeader()
                          .AllowAnyMethod();
                });
            });

            // 添加控制器
            services.AddControllers();

            // 数据库连接字符串
            var dbConnectionString = Configuration.GetConnectionString("DefaultConnection");
            services.AddDbContext<AppDbContext>(options =>
            {
                options.UseMySql(dbConnectionString, ServerVersion.AutoDetect(dbConnectionString));
            });

            // 注册服务
            services.AddTransient<IActuatorModelRepository, DbActuatorModelRepository>();
            services.AddTransient<ISqlFunctionAdapter, MySqlAdapter>();
            services.AddTransient<SQLRepository>();
            services.AddTransient<ActuatorService>();
            services.AddTransient<ScreenChartService>();
            services.AddTransient<LoadService>();
            services.AddTransient<DbTableStructureRepository>();
            services.AddTransient<DateTypeInterpreter>();
            services.AddTransient<ParamInterpreterEngine>();
            services.AddHostedService<ParamInterpreterEngine>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // 启用 CORS 中间件
            app.UseCors("AllowLocalhost5173");

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}